<template>
  <div>
    <nav-bar>
      <template v-slot:left>&lt;</template>
      <template v-slot:default>{{ title }}</template>
    </nav-bar>
    <van-address-edit
      :area-list="areaList"
      :show-delete="state.type == 'edit'"
      :address-info="state.addressInfo"
      show-set-default
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
    />
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import { onMounted, reactive, ref, toRefs, computed } from "vue";
import { Toast } from "vant";
import {
  addAddress,
  editAddress,
  getAddressDetail,
  deleteAddress,
} from "network/address";
import { useRoute, useRouter } from "vue-router";
import { areaList } from "@vant/area-data";
export default {
  name: "AddressEdit",
  components: {
    NavBar,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      searchResult: [
        {
          name: "黄龙万科中心",
          address: "杭州市西湖区",
        },
      ],
      addressInfo: {},
      type: "add",
      addressId: "",
      title: "",
    });
    onMounted(() => {
      const { type, addressId } = route.query;

      state.type = type;
      state.addressId = addressId;

      if (type == "edit") {
        getAddressDetail(addressId).then((res) => {
          console.log(res);
          const addressDetail = res;
          state.addressInfo = {
            name: addressDetail.name,
            tel: addressDetail.phone,
            province: addressDetail.province,
            city: addressDetail.city,
            county: addressDetail.county,
            addressDetail: addressDetail.address,
            isDefault: !!addressDetail.is_default,
          };
        });
      }
    });

    const title = computed(() => {
      return state.type == "add" ? "新增地址" : "编辑地址";
    });

    const onSave = (content) => {
      const params = {
        name: content.name,
        phone: content.tel,
        province: content.province,
        city: content.city,
        county: content.county,
        address: content.addressDetail,
        is_default: content.isDefault ? 1 : 0,
      };

      if (state.type == "edit") {
        // 修改地址
        editAddress(state.addressId, params);
      } else if (state.type == "add") {
        // 调用接口，添加地址
        addAddress(params);
      }

      Toast("保存成功");
      setTimeout(() => {
        router.back();
      }, 1000);
    };
    const onDelete = () => {
      deleteAddress(state.addressId).then((res) => {
        Toast("删除成功");
        setTimeout(() => {
          router.back();
        }, 1000);
      });
    };
    const onChangeDetail = (val) => {};

    return {
      onSave,
      onDelete,
      onChangeDetail,
      state,
      areaList,
      title,
    };
  },
};
</script>

<style scoped>
.van-address-edit {
  margin-top: 50px;
}
</style>
